package krasa.usefulactions.commons;

import java.io.File;
import java.io.FilenameFilter;
import java.lang.IllegalStateException;import java.lang.String;import java.util.Arrays;

/**
 * selects unique file by regexp from folder
 * 
 * @author Vojtech Krasa
 */
public class RegExpUniqueFolderFilter implements IFilePath {

	private IFilePath directory;
	private String regexp;

	public RegExpUniqueFolderFilter() {
	}

	public void setDirectory(IFilePath directory) {
		this.directory = directory;
	}

	public RegExpUniqueFolderFilter(IFilePath directory, String regexp) {
		this.regexp = regexp;
		this.directory = directory;
	}

	public void setRegexp(String regexp) {
		this.regexp = regexp;
	}

	public String getPath() {
		if (directory == null) {
			throw new IllegalStateException("directory is null");
		}
		if (regexp == null) {
			throw new IllegalStateException("regexp is null");
		}

		File dir = getDirectoryAsFile();

		File[] files = filterFilesByRegExp(dir, regexp);

		File uniqueResultFile = getUniqueResultFile(files);
		if (uniqueResultFile == null) {
			return null;
		}
        return uniqueResultFile.getAbsolutePath();
	}

	private File getUniqueResultFile(File[] files) {
		if (files.length == 0) {
//            throw new IllegalStateException("there are more no matching files in directory: " + directory);
			return null;
		}
		if (files.length > 1) {
			throw new IllegalStateException("there are more than one matching files" + Arrays.toString(files));
		}
		return files[0];
	}

	private File[] filterFilesByRegExp(File directory, final String regularExpression) {
		FilenameFilter filter = new FilenameFilter() {
			public boolean accept(File dir, String name) {
				return name.matches(regularExpression);
			}
		};

        File[] files = directory.listFiles(filter);
		if (files == null) {
			throw new IllegalStateException("not a directory :" + directory);
		}
        return files;
	}

	public File getDirectoryAsFile() {
		File dir = new File(directory.getPath());
        //todo nefacha na unixu, getCanonicalpath by mohlo pomoct...
//		if (!dir.isDirectory()) {
//			throw new IllegalStateException("is not directory:" + directory);
//		}
		return dir;
	}

}
